package captcha

import (
	"context"
	"encoding/json"
	"errors"
	"github.com/wenlng/go-captcha/v2/rotate"
	"product/common/validator"

	"product/authorization/serve/internal/svc"
	"product/authorization/serve/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CheckRotateCaptchaLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 检验旋转验证码
func NewCheckRotateCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckRotateCaptchaLogic {
	return &CheckRotateCaptchaLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CheckRotateCaptchaLogic) CheckRotateCaptcha(req *types.RotateCaptchaCheckReq) (resp *types.RotateCaptchaCheckResp, err error) {
	valid, err := validRotateInput(req)
	if !valid {
		resp.Ok = false
		return resp, err
	}
	cachedValue, err := l.svcCtx.Redis.GetCtx(l.ctx, req.CaptchaKey)
	if err != nil || validator.IsEmptyString(cachedValue) {
		resp.Ok = false
		return resp, err
	}
	var rotateCaptcha *rotate.Block
	err = json.Unmarshal([]byte(cachedValue), &rotateCaptcha)
	if err != nil {
		resp.Ok = false
		return resp, errors.New("验证码数据解析失败")
	}
	checkFlag := rotate.CheckAngle(int64(req.CaptchaCheckAngle), int64(rotateCaptcha.Angle), 2)
	resp.Ok = checkFlag
	if !checkFlag {
		resp.Ok = false
		return resp, errors.New("验证码错误")
	}
	return resp, nil
}

func validRotateInput(req *types.RotateCaptchaCheckReq) (bool, error) {
	if validator.IsEmptyString(req.CaptchaKey) {
		return false, errors.New("captchaKey不能为空")
	}
	if req.CaptchaCheckAngle == 0 {
		return false, errors.New("captchaCheckAngle不能为0")
	}
	return true, nil
}
